package com.uenpay.util.net.retrofit;

import com.socks.library.KLog;
import com.uenpay.util.crypt.AES;
import com.uenpay.util.crypt.CryptUtils;
import com.uenpay.util.net.http.HttpParam;


import org.simpleframework.xml.Serializer;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * Created by liulou on 2016/8/29.
 * desc:
 */
class UenXmlResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private static final String TAG = "UenXmlResponseBodyConverter";
    private final Class<T> cls;
    private final Serializer serializer;
    private final boolean strict;

    UenXmlResponseBodyConverter(Class<T> cls, Serializer serializer, boolean strict) {
        this.cls = cls;
        this.serializer = serializer;
        this.strict = strict;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        try {
            final String result = AES.decryptString(value.string(), CryptUtils.encryptToMD5(HttpParam.AES_Password));
            KLog.xml(TAG,result);
            T read = serializer.read(cls,new ByteArrayInputStream(result.getBytes("utf-8")), strict);
            if (read == null) {
                KLog.e("Could not deserialize body as " + cls);
                throw new IllegalStateException("Could not deserialize body as " + cls);
            }
            return read;
        } catch (RuntimeException | IOException e) {
            e.printStackTrace();
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            value.close();
        }
    }
}